import {HTTP} from '../util/http.js'

class ClassicModel extends HTTP {
    prefix = 'classic'

    getLatest(sCallback) {
        // 调用的是util/http.js里的get请求
        // 异步函数
        this.request({
            url: 'classic/latest',
            success: (res) => {
                sCallback(res)
                this._setLatestIndex(res.index)

                let key = this._getKey(res.index)
                wx.setStorageSync(key, res)
            }
        })
    }

    // 获取每一页的数据
    getClassic(index, nextOrPrevious, sCallback) {
        let key = nextOrPrevious == 'next' ? this._getKey(index+1) : this._getKey(index-1)
        let classic = wx.getStorageSync(key)
        if (!classic) {     // 没有从缓存中找到
            this.request({
                url: `classic/${index}/${nextOrPrevious}`,
                success: (res) => {
                    wx.setStorageSync(this._getKey(res.index), res)
                    sCallback(res)
                }
            })
        } else {            // 从缓存中找到
            sCallback(classic)
        }
    }

    // 判断是否第一个
    isFirst(index) {
        return index === 1 ? true : false
    }

    // 判断是否最后一个
    isLatest(index) {
        let latestIndex = this._getLatestIndex()
        return latestIndex == index ? true : false
    }

    // 设置缓存（设置latest的长度）
    _setLatestIndex(index) {
        wx.setStorageSync('latest', index)
    }

    // 获取缓存（获取latest的长度）
    _getLatestIndex() {
        let index = wx.getStorageSync('latest')
        return index
    }

    // 获取缓存里每一页的数据
    _getKey(partKey) {
        let key = this.prefix + '-' + partKey
        return key
    }

    // 获取我喜欢的书籍列表
    getMyFavor(success){
        let params={
            url:'classic/favor',
            success:success
        }
        this.request(params)
    }

    // 获取喜欢的详情
    getById(cid, type, success) {
        let params = {
            url: 'classic/' + type + '/' + cid,
            success: success
        }
        this.request(params)
    }
}

export {ClassicModel}